package com.taorenqi.data.converter;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;

import java.io.IOException;
import java.io.StringReader;
import java.net.URLDecoder;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by Administrator on 2017-06-13.
 */

public class AesGsonResponseBodyConverter <T> implements Converter<ResponseBody, T> {

    private final Gson gson;
    private final TypeAdapter<T> adapter;

    public AesGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody responseBody) throws IOException {
        try {
            // TODO: 2016/12/26 设计你自己的响应体解密算法，下面使用了Base64解码
//            String response= Jiemi.GetDesDecrypt(URLDecoder.decode(responseBody.string(), "utf-8"));
//            String strResult= Jiemi.decodeData(URLDecoder.decode(responseBody.string(), "utf-8"));
//            String strResult = response.substring(1,response.length() - 1);
//            Log.e("response",strResult);

//            InputStream inputStream = new ByteArrayInputStream(strResult.getBytes());
//            Reader reader = new InputStreamReader(inputStream, "utf-8");
//            JsonReader jsonReader = gson.newJsonReader(reader);
            JsonReader jsonReader = gson.newJsonReader(new StringReader(responseBody.string()));
//            JsonReader jsonReader = new JsonReader(new StringReader(strResult));
            try {
                return adapter.read(jsonReader);
            } finally {
                responseBody.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}